package net.sansi.v3correctserver.service.websocket.updateprogress;

/**
 * Created by Fang
 * create time : 2025/2/17
 * IDE : IntelliJ IDEA
 * <p>
 * 更新任务进度 websocket 订阅
 */

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;

@Service
@Slf4j
public class UpdateProgressWSHandler extends TextWebSocketHandler {


    /**
     * 获取该订阅的会话连接管理器
     *
     * @return 连接管理器
     */
    private UpdateProgressWSManager getManager() {
        return UpdateProgressWSManager.getInstance();
    }

    /**
     * 处理接收到的信息
     *
     * @param session 会话
     * @param message 消息
     * @throws IOException 异常
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
        // 处理接收到的消息
        String payload = message.getPayload();
        log.info("Received message [{}]: {}", session.getRemoteAddress(), payload);
        getManager().trigger(payload);
    }

    /**
     * 连接建立后的处理
     *
     * @param session 会话
     * @throws Exception 异常
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 连接建立后的处理
        getManager().addSession(session);
        log.info("New connection established [{}]", session.getRemoteAddress());
    }

    /**
     * 连接关闭后的处理
     *
     * @param session 会话
     * @param status  状态
     * @throws Exception 异常
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        getManager().removeSession(session);
        // 连接关闭后的处理
        log.info("Connection closed [{}]", session.getRemoteAddress());
    }


}
